<?php
/*
 * kernel/object.options.php
 *
 * This code is distributed and used under the GNU GPL v2 License,
 * please, read file LICENSE, which is situated in root directory,
 * or in "LICENSE" directory with most acceptable translation for you
 *
 * 
 *
 * Copyright (C) 2010, Taras Kudla
 *
 */
class gOptions extends gKernel {
	
	private $table="systemoptions";
	private $SYS=array();
	private $KernelName="core";
	
	public function set($key,$value=null,$item=null){
		$item= ($item==null)?( $this->core->getenvlayer()==_ENV_MOD?$this->core->getenvcaller("mod"):$this->KernelName ):$this->core->escapeString($item);
		$key=$this->core->escapeString($key);
		if(is_string($value))$value=$this->core->escapeString($value);
		if( $this->core->dbo->select($this->table,"value"," where item='".$item."' and keyname='".$key."'",_RESULT_BOOL) ){
			$this->core->dbo->update($this->table," set value='".$value."' where keyname='".$key."' and item='".$item."'");
		}
		else {
			$this->core->dbo->insert($this->table,array("item"=>$item,"keyname"=>$key,"value"=>$value));
		}
		return true;
	}
	
	public function get($key=null,$item=null,$where = null){
		$item= ($item==null)?( $this->core->getenvlayer()==_ENV_MOD?$this->core->getenvcaller("mod"):$this->KernelName ):$this->core->escapeString($item);
		$where = ( $where==null)?null:" and value='".$this->core->escapeString($where)."' ";		
		if($key==null){
			$sql=" where item='".$item."' $where limit 200 offset 0";
		}
		else {
			$sql=" where item='".$item."' and keyname='".$this->core->escapeString($key)."' $where limit 1 offset 0";
		}
		$query=$this->core->dbo->select($this->table,"keyname,value",$sql,_RESULT_PAIRS);
		$num = count($query);
		if( $num == 0 ){
			return false;
		} else if( $num==1 && $key!=null){
			return $query[$key];
		} else
			return $query;
	}
	
	public function Delete($key=null,$item=null){
		$item= ($item==null)?( $this->core->getenvlayer()==_ENV_MOD?$this->core->getenvcaller("mod"):$this->KernelName ):$this->core->escapeString($item);		
		if($key==null)
		$this->core->dbo->delete($this->table,"where item='".$item."'");
		else
		$this->core->dbo->delete($this->table," where item='".$item."' and keyname='".$key."' ");
		return true;
	}
	
	public function LoadBasic(){
		
		$_=$this->Get("KERNEL");
		if(is_array($_)){
			$this->SYS=$_;
		}
	}
	
	public function & GetAll(){
		$item=($this->core->getenvlayer()==_ENV_KERNEL)?$this->KernelName:$this->core->getenvcaller("mod");
		$query=$this->core->dbo->select($this->table,"keyname,value"," where item='".$item."'",_RESULT_PAIRS);
		$this->core->DEBUG("OPTIONS","Options for module '".$item."' loaded");
		return $query;
	}
	
	public function GetSYS($key){
		return (isset($this->SYS[$key])?$this->SYS[$key]:false);
	}

}